/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.news;

import com.blandware.atleap.common.NewsModuleConstants;
import com.blandware.atleap.common.util.DateUtil;
import com.blandware.atleap.model.news.NewsItem;
import com.blandware.atleap.service.news.NewsManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.news.NewsItemForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.news.NewsModuleWebConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.RequestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * <p>Returns page which allows editing of news item annotation in selected
 * languages</p>
 *
 * <p><a href="CallUpdateNewsItemAnnotationAction.java.html"></a><i>View source</i></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.13 $ $Date: 2008/04/29 17:51:52 $
 * @struts.action path="/news/callUpdateItemAnnotation"
 * input="inputForward"
 * name="newsItemForm"
 * validate="false"
 * roles="news-item-update"
 * scope="request"
 * @struts.action-forward name="inputForward"
 * path=".news.updateItem"
 * @struts.action-forward name="updateNewsItemAnnotation"
 * path=".news.updateItemAnnotation"
 * @struts.action-forward name="listNewsItems"
 * path="/news/listItems.do"
 * redirect="true"
 */
public final class CallUpdateNewsItemAnnotationAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		request.getSession().removeAttribute(NewsModuleWebConstants.NEWS_ITEM_SUBMITTED_ACTION_KEY);

		if ( isCancelled(request) ) {
            request.getSession().removeAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_ANNOTATION_KEY);
            request.getSession().removeAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_BODY_KEY);
            if ( request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY) != null ) {
				String redirectUrl = (String) request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(redirectUrl, true);
			}
			return mapping.findForward("listNewsItems");
		}

		if ( request.getSession().getAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY) == null ) {
			List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
			request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);
		}

		NewsItemForm newsItemForm = (NewsItemForm) form;

        // Check whether user came here not from previous page (or he switched
        // edit mode/language during editing news item)
        String localesMode = newsItemForm.getLocalesMode();
        if (!"current".equalsIgnoreCase(localesMode) && !"all".equalsIgnoreCase(localesMode) && newsItemForm.getAnnotationCheckedBoxes().size() == 0) {
            request.setAttribute("beginPage", mapping.findForward("listNewsItems").getPath());
            return mapping.findForward("unsatisfiablePage");
        }

		if ( !WebappUtil.hasCorrectValues(newsItemForm.getTitleMap()) ) {
			// title must be specified

            // check 'check all' ckeckbox if needed
            newsItemForm.setAllCheckedFlagForAnnotationCheckboxes(request, localesMode);

			ActionMessages errors = new ActionMessages();
			errors.add("title", new ActionMessage("core.commons.errors.required", getMessage(request, "news.form.title")));
			saveErrors(request, errors, false);
			saveToken(request);
			return mapping.getInputForward();
		}

		// check news item existence, because it might be deleted by another transaction
		Long newsItemId;
		if ( !GenericValidator.isBlankOrNull(newsItemForm.getId()) ) {
			newsItemId = Long.valueOf(newsItemForm.getId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing news item ID. Returning to list");
			}
			return mapping.findForward("listNewsItems");
		}

		NewsManager newsManager = (NewsManager) getBean(NewsModuleConstants.NEWS_MANAGER_BEAN);
		NewsItem newsItem = newsManager.retrieveNewsItem(newsItemId);
		if ( newsItem == null ) {
			ActionMessages errors = new ActionMessages();
			errors.add("newsItemNotFound", new ActionMessage("news.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listNewsItems");
		}

        // check publication and expiration dates
        Date publicationDate;
        Date expirationDate;
        boolean publicationDateIsValid = false;
        try {
            publicationDate = DateUtil.parseDate(newsItemForm.getPublicationDate(), RequestUtils.getUserLocale(request, null));
            publicationDateIsValid = true;
            expirationDate = DateUtil.parseDate(newsItemForm.getExpirationDate(), RequestUtils.getUserLocale(request, null));
        } catch (ParseException e) {
            ActionMessages errors = new ActionMessages();
            errors.add("newsItemInvalidDate", new ActionMessage("core.commons.errors.customDate",
                        publicationDateIsValid ? newsItemForm.getExpirationDate() : newsItemForm.getPublicationDate()));
            saveErrors(request, errors);
            saveToken(request);
            return mapping.getInputForward();
        }


        if ( publicationDate.compareTo(expirationDate) >= 0 ) {
            // check 'check all' ckeckbox if needed
            newsItemForm.setAllCheckedFlagForAnnotationCheckboxes(request, localesMode);

            ActionMessages errors = new ActionMessages();
            errors.add("newsItemInvalidDate", new ActionMessage("news.errors.invalidPublicationDate"));
            saveErrors(request, errors);
            saveToken(request);
            return mapping.getInputForward();
        }

        Date now = new Date();
        if (expirationDate.compareTo(now) <= 0) {
            // check 'check all' ckeckbox if needed
            newsItemForm.setAllCheckedFlagForAnnotationCheckboxes(request, localesMode);

            ActionMessages errors = new ActionMessages();
            errors.add("newsItemInvalidDate", new ActionMessage("news.errors.invalidExpirationDate"));
            saveErrors(request, errors);
            saveToken(request);
            return mapping.getInputForward();
        }

        if (newsItemForm.getAnnotationCheckedBoxes().size() != 0) {
            newsItemForm.setBodyCheckedBoxes(newsItemForm.getAnnotationCheckedBoxes());
        }
        newsItemForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);

		if ( request.getSession().getAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_ANNOTATION_KEY) != null ) {
			Map mergedAnnotation = (Map) request.getSession().getAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_ANNOTATION_KEY);
			newsItemForm.setAnnotationMap(mergedAnnotation);
			request.getSession().removeAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_ANNOTATION_KEY);
		}

		saveToken(request);
		return mapping.findForward("updateNewsItemAnnotation");
	}
}
